package com.hand.wfive.activity.edit

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.hand.wfive.App
import com.rxjava.rxlife.RxLife
import com.hand.wfive.R
import com.hand.wfive.activity.sign.SignActivity
import com.hand.wfive.ad.AdActivity
import com.hand.wfive.adapter.FileEditAdapter
import com.hand.wfive.adapter.FileSelectAdapter
import com.hand.wfive.dialog.MsgDialog
import com.hand.wfive.entity.FileEvent
import com.hand.wfive.entity.FileListModel
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.Params
import com.hand.wfive.entity.SignLibEvent
import com.hand.wfive.entity.WordImagesModel
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.util.FileUtils
import com.hand.wfive.util.click.singleClick
import com.hand.wfive.util.oss.OssCallBack
import com.hand.wfive.util.oss.OssRequest
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableSource
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_file_edit.topBar
import kotlinx.android.synthetic.main.activity_file_select.btn_sure
import kotlinx.android.synthetic.main.activity_file_select.ll_action
import kotlinx.android.synthetic.main.activity_file_select.rl_bottom
import kotlinx.android.synthetic.main.fragment_file_item.recycler_file
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivity
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.asClass
import java.io.File

class FileSelectActivity : AdActivity() {
    protected lateinit var mAdapter: FileSelectAdapter
    private var mPage = 1
    var fileList = ArrayList<FileModel>()
    var mType = 0//0签字1签章
    var mFileModel: FileModel? = null

    companion object {
        fun show(context: Context, type: Int) {
            context.startActivity<FileSelectActivity>("type" to type)
        }
    }

    override fun init() {
        mType = intent.getIntExtra("type", 0)
        fileList.clear()
        topBar.addLeftBackImageButton().singleClick { doOnBackPressed() }
        topBar.setTitle("选择文件")
        btn_sure.singleClick {
            if (mFileModel != null) {
                sign(mFileModel!!)
            }
        }
        mAdapter = FileSelectAdapter()
        mAdapter.addChildClickViewIds(R.id.iv_more)
        mAdapter.setOnItemChildClickListener { _, _, position ->
            val model = mAdapter.getItem(position)
            model.select = !model.select

            for (m in fileList.indices) {
                if (m != position) {
                    fileList[m].select = false
                }
            }
            show(model)
            mAdapter.notifyDataSetChanged()
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            val model = mAdapter.getItem(position)
            model.select = !model.select

            for (m in fileList.indices) {
                if (m != position) {
                    fileList[m].select = false
                }
            }
            show(model)
            mAdapter.notifyDataSetChanged()


        }
        recycler_file.layoutManager = LinearLayoutManager(mContext)
        (recycler_file.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        recycler_file.adapter = mAdapter
        mAdapter.setEmptyView(getEmptyView())

        mAdapter.loadMoreModule.isEnableLoadMore = true
        mAdapter.loadMoreModule.setOnLoadMoreListener {
            loadData()
        }

        loadData()
    }

    @SuppressLint("CheckResult")
    private fun sign(model: FileModel) {
        when (model.type) {
            Params.fileTypePdf -> {
                pdfSign(model)
            }

            Params.fileTypeWord -> {
                RxHttp.postForm(ApiConfig.getWordImageData)
                    .add("userId", UserManager.getInstance().userId)
                    .add("cloudFileId", model.id)
                    .add("appid", LoginConfig.AppId)
                    .asClass(WordImagesModel::class.java)
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        when (it.code) {
                            200 -> {
                                SignActivity.show(mContext, model)
                            }

                            203 -> {
                                showNormalTip("此文档正在上传，请稍后")
                            }

                            else -> {
                                showNormalTip("此文档暂不可签名")
                            }
                        }

                    }

            }

            else -> {
                SignActivity.show(mContext, model)
            }
        }
    }

    private fun pdfSign(model: FileModel) {
        val suffix = model.fileId.substring(model.fileId.lastIndexOf("."))
        model.filePath = if (model.fileName.endsWith(suffix, true)) {
            "${App.getContext().cacheSignPath}/${model.fileName}"
        } else {
            "${App.getContext().cacheSignPath}/${model.fileName}${suffix}"
        }
        val file = File(model.filePath)
        if (file.exists() && FileUtils.getFileSize(file) == model.size) {
            SignActivity.show(mContext, model)
        } else {
            showLoadingTipC()
            OssRequest.getInstance().dowloadFile(
                model.fileId, model.filePath, object : OssCallBack {
                    override fun onSuccess() {
                        dismissTip()
                        SignActivity.show(mContext, model)
                    }

                    override fun onFailure(msg: String) {
                        showNormalTip(if (msg.contains("下载")) "打开失败" else msg)
                    }
                })
        }
    }

    private fun show(model: FileModel) {
        if (model.select) {
            mFileModel = model
            ll_action.visibility = View.VISIBLE
        } else {
            mFileModel = null
            ll_action.visibility = View.GONE
        }
    }

    private fun loadData() {


        RxHttp.postForm(ApiConfig.getUserFileList)
            .add("appid", LoginConfig.AppId)
            .add("userId", UserManager.getInstance().userId)
            .add("type", Params.fileTypeAll)
            .add("pageSize", 20)
            .add("page", mPage)
            .asClass<FileListModel>()
            .to(RxLife.toMain(this))
            .subscribe({
                Log.e("loadData", it.toString())
                if (it.code == ApiConfig.SUCCESSCODE) {
                    if (mPage == 1) {
                        fileList.clear()
                        fileList.addAll(it.data.records)
                        mAdapter.setNewInstance(fileList)
                    } else {
                        fileList.addAll(it.data.records)
                        mAdapter.notifyDataSetChanged()
//                        mAdapter.addData(it.data.records)
                    }
                    if (it.data.records.isEmpty()) {
                        mAdapter.loadMoreModule.loadMoreEnd()
                    } else {
                        mPage++
                        mAdapter.loadMoreModule.loadMoreComplete()
                    }
                } else resetPage()
            }, {
                resetPage()
            })
    }

    private fun getEmptyView(): View {
        val view = LayoutInflater.from(mContext)
            .inflate(R.layout.item_file_empty, recycler_file, false)
        view.find<TextView>(R.id.tv_tip).text = "暂无数据"
        return view
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun doSignLibEvent(event: SignLibEvent) {
        if (Params.fileTypeAll == event.type) {
            mPage = 1
            loadData()
        }
    }

    private fun resetPage() {
        mPage--
        if (mPage < 1) mPage = 1
        mAdapter.loadMoreModule.loadMoreComplete()
    }

    override fun getContentViewId(): Int {
        return R.layout.activity_file_select
    }
}